﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://www.codeplex.com/EmlenMud
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Threading;
using BrainTechLLC.ThreadSafeObjects;
#if USE_HYPER
using Hyper.ComponentModel;
#endif

namespace BrainTechLLC.Logging
{
    /// <summary>
    /// Implementation of ILogger that logs messages to memory and calls a delegate whenever a new log entry is written
    /// </summary>    
    [Serializable]
    [DataContract]
    public class OutputLogger : LoggerBase, ILogger
    {
        public Action<string> WriteOutput { get; set; }

        public static void CreateAndRegisterOutputLogger(Action<string> writeOutputDel)
        {
            OutputLogger logger = new OutputLogger(writeOutputDel);
            logger.BeginLogging();
            GlobalLogger.RegisterLogger(logger);
        }

        public OutputLogger(Action<string> writeOutputDel)
            : base()
        {
            WriteOutput = writeOutputDel;
        }

        protected override void LogListener()
        {
            List<LogMessage> logEntries = new List<LogMessage>();

            try
            {
                while (!WantExit)
                {
                    while (!WantExit && _logOutput.Count == 0) { Thread.Sleep(40); }

                    LogMessage logEntry;

                    while (!WantExit && _logOutput.Dequeue(out logEntry))
                    {
                        WriteOutput(logEntry.ToString());
                    }
                }
            }
            catch (Exception)
            {
            }
        }
    }
}
